package com.guandi.geekbrowser.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.guandi.geekbrowser.Utils.DESHelper;
import com.guandi.geekbrowser.Utils.EasyUtil;
import com.guandi.geekbrowser.primary.entity.*;
import com.guandi.geekbrowser.primary.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.websocket.server.PathParam;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Optional;

@Controller
public class TaskController {

    @Autowired
    private TaskItemService taskItemService;
    @Autowired
    private TabService tabService;
    @Autowired
    private TaskService taskService;
    @Autowired
    private DetailsService detailsService;
    @Autowired
    private TaskManageService taskManageService;

    private DESHelper desHelper = new DESHelper("zDsGrVKQ");

    @RequestMapping(value = "/addTaskItem", method = RequestMethod.POST)
    @ResponseBody
    public String addTaskItem(@RequestBody JSONObject jsonObject) {
        String url = jsonObject.getString("url");
        String asinCode = jsonObject.getString("asinCode");
        String userId = jsonObject.getString("userId");
        String taskName = jsonObject.getString("taskName");
        Integer totalCount = jsonObject.getInteger("totalCount");
        Integer type = jsonObject.getInteger("type");
        Message message = new Message();
        if (!EasyUtil.isEmpty(url) && !EasyUtil.isEmpty(asinCode) && !EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(taskName)) {
//            userId = EasyUtil.decryptProperty(userId);
            userId = desHelper.decrypt(userId);
            TaskItem taskItem = new TaskItem();
            taskItem.setUrl(url);
            taskItem.setAsinCode(asinCode);
            taskItem.setTotalCount(totalCount);
            taskItem.setUserId(userId);
            taskItem.setDate(new Date());
            taskItem.setFinishCount(0);
            taskItem.setType(type);
            taskItem.setTaskName(taskName.trim());
            taskItemService.save(taskItem);
            message.setMessage("添加成功!");
            message.setSuccess(true);
            message.setParams(taskName.trim());
        } else {
            message.setSuccess(false);
            message.setMessage("参数错误!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/getTaskItemList", method = RequestMethod.POST)
    @ResponseBody
    public Page<TaskItem> getTaskItemList(@RequestBody JSONObject jsonObject) {
        Integer pageNumber = jsonObject.getInteger("pageNumber");
        Integer pageSize = jsonObject.getInteger("pageSize");
        String userId = jsonObject.getString("userId");
        String taskName = jsonObject.getString("taskName");
        Integer type = jsonObject.getInteger("type");
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(taskName)) {
            userId = desHelper.decrypt(userId);
            Page<TaskItem> likedPage = taskItemService.findAllByUserIdAndTypeAndTaskNamePage(userId, type,
                    taskName, pageNumber, pageSize);
            return likedPage;
        }
        return null;
    }

    @RequestMapping(value = "/addTaskName", method = RequestMethod.POST)
    @ResponseBody
    public String addLikeTab(@RequestBody JSONObject jsonObject) {
        String taskName = jsonObject.getString("taskName");
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Integer type = jsonObject.getInteger("type");
        Message message = new Message();
        if (!EasyUtil.isEmpty(taskName) && !EasyUtil.isEmpty(userId)) {
            List<Task> list = taskService.findByNameAndUserIdAndType(taskName, userId, type);
            if (list == null) {
                if (type == 0 || type == 1) {
                    userId = desHelper.decrypt(userId);
                    Task taskTemp = new Task();
                    taskTemp.setDate(new Date());
                    taskTemp.setName(taskName);
                    taskTemp.setType(type);
                    taskTemp.setUserId(userId);
                    taskTemp.setCountry(country);
                    taskService.save(taskTemp);
                    message.setMessage("添加成功!");
                    message.setSuccess(true);
                    message.setParams(taskName.trim());
                } else {
                    message.setSuccess(false);
                    message.setMessage("任务类型错误!");
                }
            } else {
                message.setSuccess(false);
                message.setMessage("任务名已存在!");
            }
        } else {
            message.setSuccess(false);
            message.setMessage("参数错误!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/getTaskListTemp", method = RequestMethod.POST)
    @ResponseBody
    public List<Task> getTaskListTemp(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        Integer type = jsonObject.getInteger("type");
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            List<Task> taskList = taskService.findByUserIdAndType(userId, type);
            return taskList;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "/getTaskItems", method = RequestMethod.POST)
    @ResponseBody
    public List<TaskItem> getTaskItems(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        Integer type = jsonObject.getInteger("type");
        String taskName = jsonObject.getString("taskName");
        List<TaskItem> list = taskItemService.findAllByUserIdAndTypeAndTaskName(userId, type, taskName);
        return list;
    }

    @RequestMapping(value = "/updateLikeNotes", method = RequestMethod.POST)
    @ResponseBody
    public String updateLikeNotes(@RequestBody JSONObject jsonObject) {
        Object o = jsonObject.get("taskItem");
        String userId = jsonObject.getString("userId");
        String s = JSONObject.toJSONString(o);
        TaskItem taskItem = JSON.toJavaObject(JSONObject.parseObject(s), TaskItem.class);
        if (taskItem != null) {
            userId = desHelper.decrypt(userId);
            Integer integer = taskItemService.updateLikedNotesByIdAndUserId(taskItem.getNotes(), taskItem.getId(), userId);
            return integer.toString();
        }
        return null;
    }

    @RequestMapping(value = "/updateLike", method = RequestMethod.POST)
    @ResponseBody
    public String updateLike(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        Object o = jsonObject.get("taskItem");
        String s = JSONObject.toJSONString(o);
        TaskItem taskItem = JSON.toJavaObject(JSONObject.parseObject(s), TaskItem.class);
        if (taskItem.getId() != null) {
            userId = desHelper.decrypt(userId);
            Integer integer = taskItemService.updateLikedByIdAndUserId(taskItem.getUrl(), taskItem.getAsinCode(), taskItem.getTotalCount(), taskItem.getId(), userId);
            return "修改成功!" + integer.toString();
        }
        return "修改失败!";
    }

    @RequestMapping(value = "/delLike", method = RequestMethod.POST)
    @ResponseBody
    public String delLike(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        Long id = jsonObject.getLong("id");
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            Integer integer = taskItemService.deleteByIdAndUserId(id, userId);
            return integer.toString();
        }
        return "修改失败!";
    }

    @RequestMapping(value = "/exportLikeFile", method = RequestMethod.GET)
    @ResponseBody
    public String exportLikeFile(HttpServletResponse response, @PathParam("userId") String userId, @PathParam("type") Integer type) {
        if (!EasyUtil.isEmpty(userId)) {
            userId = desHelper.decrypt(userId);
            List<TaskItem> taskItemList = taskItemService.findAllByUserIdAndType(userId, type);
            EasyUtil.exportLikeExcel("点赞信息", response, taskItemList);
        }
        return "export file";
    }

    @RequestMapping(value = "/inputLikeFile", method = RequestMethod.POST)
    @ResponseBody
    public String inputLikeFile(@RequestParam("file") MultipartFile file, @RequestParam("userId") String userId, @RequestParam("type") Integer type,
                                @RequestParam("curTaskName") String curTaskName) {
        Message message = new Message();
        if (!file.isEmpty()) {
            try {
                userId = desHelper.decrypt(userId);
                List<TaskItem> list = EasyUtil.readLikeExcel(file, type, curTaskName, userId);
                if (list != null & list.size() > 0) {
                    taskItemService.saveAll(list);
                    message.setSuccess(true);
                    message.setMessage("添加成功!");
                } else {
                    message.setSuccess(false);
                    message.setMessage("内容为空!");
                }
            } catch (FileNotFoundException e) {
//                e.printStackTrace();
                message.setSuccess(false);
                message.setMessage("上传失败!" + e.getMessage());
            } catch (IOException e) {
//                e.printStackTrace();
                message.setSuccess(false);
                message.setMessage("上传失败!" + e.getMessage());
            }
        } else {
            message.setSuccess(false);
            message.setMessage("上传失败，因为文件是空的.!");
        }
        return JSONObject.toJSONString(message);
    }

    @RequestMapping(value = "/getTaskTabList", method = RequestMethod.POST)
    @ResponseBody
    public String getTaskTabList(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String country = jsonObject.getString("country");
        Integer type = jsonObject.getInteger("type");
        if (!EasyUtil.isEmpty(userId)&&!EasyUtil.isEmpty(country)) {
            userId = desHelper.decrypt(userId);
            List<Task> list = taskService.findByUserIdAndTypeAndCountry(userId, type, country);
            return JSONObject.toJSONString(list);
        }
        return null;
    }

    @RequestMapping(value = "/delTask", method = RequestMethod.POST)
    @ResponseBody
    public String delTask(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        String taskName = jsonObject.getString("taskName");
        if (!EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(taskName)) {

        }
        return "";
    }



    @RequestMapping(value = "/updateTaskStatus", method = RequestMethod.POST)
    @ResponseBody
    public String updateTaskStatus(@RequestBody JSONObject jsonObject) {
        String detailId = jsonObject.getString("detailId");
        String userId = jsonObject.getString("userId");
        String taskItemId = jsonObject.getString("taskItemId");
        if (!EasyUtil.isEmpty(detailId) && !EasyUtil.isEmpty(userId) && !EasyUtil.isEmpty(taskItemId)) {
            userId = desHelper.decrypt(userId);
            TaskManage taskManageTemp = new TaskManage();
            taskManageTemp.setDetailId(Long.parseLong(detailId));
            taskManageTemp.setUserId(userId);
            taskManageTemp.setTaskItemId(Long.parseLong(taskItemId));
            taskManageService.save(taskManageTemp);
            return "更新成功!";
        } else {
            return "参数错误!";
        }
    }

    @RequestMapping(value = "/updateTaskItemStatus", method = RequestMethod.POST)
    @ResponseBody
    public String updateTaskItemStatus(@RequestBody JSONObject jsonObject) {
        String userId = jsonObject.getString("userId");
        Long taskItemId = jsonObject.getLong("taskItemId");
        Integer type = jsonObject.getInteger("type");
        Integer finishCount = jsonObject.getInteger("finishCount");
        if (!EasyUtil.isEmpty(userId) && finishCount != null && type != null) {
            userId = desHelper.decrypt(userId);
            TaskItem taskItem = taskItemService.findAllByUserIdAndTypeAndId(userId, type, taskItemId);
            if (taskItem != null) {
                if (finishCount.equals(taskItem.getTotalCount())) {
                    taskItem.setFinishCount(finishCount);
                    taskItem.setFinish(true);
                } else {
                    taskItem.setFinishCount(finishCount);
                }
                taskItemService.save(taskItem);
            } else {
                return "任务不存在!";
            }
        }
        return "参数错误!";
    }
}
